<?php
namespace app\controller\crm;

use app\BaseController;
use app\model\crm\Customer;
use app\model\crm\Order;
use app\model\crm\Review;
use app\model\crm\Followup;
use think\facade\Db;

class Stats extends BaseController
{
    /**
     * 获取CRM概览统计
     */
    public function overview()
    {
        try {
            $userId = $this->getUserId();
            $departmentId = $this->getUserDepartmentId();

            // 获取客户统计
            $customerStats = $this->getCustomerStats($userId, $departmentId);

            // 获取订单统计
            $orderStats = $this->getOrderStats($userId, $departmentId);

            // 获取跟进统计
            $followupStats = $this->getFollowupStats($userId, $departmentId);
            
            // 计算今日跟进数
            $todayStart = strtotime('today');
            $todayWhere = [];
            if (!$this->isAdmin()) {
                if ($this->isManager()) {
                    $todayWhere[] = ['department_id', '=', $departmentId];
                } else {
                    $todayWhere[] = ['user_id', '=', $userId];
                }
            }
            $todayFollowups = Db::name('crm_followup')
                ->where($todayWhere)
                ->where('followup_time', '>=', $todayStart)
                ->count();

            // 调整数据格式，使其与前端期望一致
            $data = [
                // 客户统计数据
                'totalCustomers' => $customerStats['total'],
                'cooperatedCustomers' => $customerStats['cooperation'],

                // 跟进统计数据
                'todayFollowups' => $todayFollowups,

                // 订单统计数据
                'totalOrders' => $orderStats['total'],
                'pendingOrders' => $orderStats['pending'],
                'approvedOrders' => $orderStats['completed'], // 已完成订单作为已通过
                'rejectedOrders' => 0 // 暂无拒绝统计
            ];

            return $this->success($data, '获取统计成功');
        } catch (\Exception $e) {
            return $this->error('获取统计失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取CRM概览统计（兼容旧接口）
     */
    public function dashboard()
    {
        return $this->overview();
    }

    /**
     * 获取跟进趋势统计
     */
    public function followupTrend()
    {
        try {
            $userId = $this->getUserId();
            $departmentId = $this->getUserDepartmentId();

            // 获取过去7天的跟进统计
            $days = 7;
            $dates = [];
            $visit = [];
            $phone = [];
            $wechat = [];
            $email = [];

            for ($i = $days - 1; $i >= 0; $i--) {
                $date = date('Y-m-d', strtotime("-$i days"));
                $nextDate = date('Y-m-d', strtotime("-$i days +1 day"));
                $dates[] = $date;

                // 将日期字符串转换为时间戳
                $startTimestamp = strtotime($date);
                $endTimestamp = strtotime($nextDate);
                
                $baseWhere = [
                    ['followup_time', '>=', $startTimestamp],
                    ['followup_time', '<', $endTimestamp]
                ];

                // 数据权限控制
                $where = $baseWhere;
                if (!$this->isAdmin()) {
                    if ($this->isManager()) {
                        $where[] = ['department_id', '=', $departmentId];
                    } else {
                        // 普通员工只能看到自己的跟进记录，使用user_id字段
                        $where[] = ['user_id', '=', $userId];
                    }
                }

                // 统计不同类型的跟进记录
                // 根据Followup模型中的定义：1=电话联系, 2=微信沟通, 3=邮件联系, 4=上门拜访, 5=会议沟通
                $visitWhere = $where;
                $visitWhere[] = ['followup_type', '=', 4]; // 上门拜访
                $visit[] = Db::name('crm_followup')->where($visitWhere)->count();

                $phoneWhere = $where;
                $phoneWhere[] = ['followup_type', '=', 1]; // 电话联系
                $phone[] = Db::name('crm_followup')->where($phoneWhere)->count();

                $wechatWhere = $where;
                $wechatWhere[] = ['followup_type', '=', 2]; // 微信沟通
                $wechat[] = Db::name('crm_followup')->where($wechatWhere)->count();

                $emailWhere = $where;
                $emailWhere[] = ['followup_type', '=', 3]; // 邮件联系
                $email[] = Db::name('crm_followup')->where($emailWhere)->count();
            }

            // 返回前端期望的数据格式
            $data = [
                'dates' => $dates,
                'visit' => $visit,
                'phone' => $phone,
                'wechat' => $wechat,
                'email' => $email
            ];

            return $this->success($data, '获取跟进趋势统计成功');
        } catch (\Exception $e) {
            return $this->error('获取跟进趋势统计失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取订单分析统计
     */
    public function orderAnalysis()
    {
        try {
            $userId = $this->getUserId();
            $departmentId = $this->getUserDepartmentId();

            // 按月份统计订单金额（最近6个月）
            $months = [];
            $litigation = [];
            $nonLitigation = [];
            
            for ($i = 5; $i >= 0; $i--) {
                $month = date('Y-m', strtotime("-$i months"));
                $nextMonth = date('Y-m', strtotime("-$i months +1 month"));
                $months[] = $month;

                $baseWhere = [
                    ['create_time', '>=', $month],
                    ['create_time', '<', $nextMonth]
                ];

                // 数据权限控制
                $where = $baseWhere;
                if (!$this->isAdmin()) {
                    if ($this->isManager()) {
                        $where[] = ['department_id', '=', $departmentId];
                    } else {
                        // 普通员工只能看到自己的订单，使用signer_id字段
                        $where[] = ['signer_id', '=', $userId];
                    }
                }

                // 统计诉讼业务（假设order_type=1为诉讼）
                $litigationWhere = $where;
                $litigationWhere[] = ['order_type', '=', 1];
                $litigationAmount = Db::name('crm_order')->where($litigationWhere)->sum('total_amount');
                $litigation[] = $litigationAmount ? $litigationAmount : 0;

                // 统计非诉业务（假设order_type=2为非诉）
                $nonLitigationWhere = $where;
                $nonLitigationWhere[] = ['order_type', '=', 2];
                $nonLitigationAmount = Db::name('crm_order')->where($nonLitigationWhere)->sum('total_amount');
                $nonLitigation[] = $nonLitigationAmount ? $nonLitigationAmount : 0;
            }

            // 返回前端期望的数据格式
            $data = [
                'months' => $months,
                'litigation' => $litigation,
                'nonLitigation' => $nonLitigation
            ];

            return $this->success($data, '获取订单分析统计成功');
        } catch (\Exception $e) {
            return $this->error('获取订单分析统计失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取客户统计
     */
    private function getCustomerStats($userId, $departmentId)
    {
        $customerModel = new Customer();

        // 构建查询条件
        $where = [];
        if (!$this->isAdmin()) {
            if ($this->isManager()) {
                // 部门经理可以看到部门内所有客户
                // 需要通过JOIN admin表来获取department_id
                $where[] = ['c.user_id', 'in', function($q) use ($departmentId) {
                    $q->table('oa_admin')->where('did', $departmentId)->field('id');
                }];
            } else {
                // 普通员工只能看到自己的客户，使用user_id字段
                $where[] = ['c.user_id', '=', $userId];
            }
        }

        // 总客户数
        $total = $customerModel
            ->alias('c')
            ->where($where)
            ->count();

        // 已合作客户数 (使用is_cooperation字段)
        $cooperation = $customerModel
            ->alias('c')
            ->where($where)
            ->where('c.is_cooperation', 1)
            ->count();

        // 公海客户数 (status = 4)
        $public = $customerModel
            ->alias('c')
            ->where($where)
            ->where('c.status', 4)
            ->count();

        // 本周新增客户数
        $weekStart = strtotime('monday this week');
        $weekNew = $customerModel
            ->alias('c')
            ->where($where)
            ->where('c.create_time', '>=', $weekStart)
            ->count();

        return [
            'total' => $total,
            'cooperation' => $cooperation,
            'public' => $public,
            'week_new' => $weekNew
        ];
    }

    /**
     * 获取订单统计
     */
    private function getOrderStats($userId, $departmentId)
    {
        // 使用Db而不是Model，因为需要JOIN来查询department
        $db = Db::name('crm_order');

        // 基础查询条件：过滤已删除的订单
        $query = $db->whereExp('delete_time', 'IS NULL OR delete_time = 0');

        // 数据权限控制
        if (!$this->isAdmin()) {
            if ($this->isManager()) {
                // 部门经理：需要JOIN admin表来获取department_id
                $query->alias('o')
                    ->leftJoin('admin u', 'o.signer_id = u.id')
                    ->where('u.did', $departmentId);
            } else {
                // 普通员工只能看到自己的订单，使用signer_id字段
                $query->where('signer_id', $userId);
            }
        }

        // 总订单数
        $total = $query->count();

        // 总金额
        $totalAmount = $query->sum('total_amount');

        // 待审核订单数 (使用approval_status字段)
        $pending = $query->where('approval_status', 1)->count();

        // 已完成订单数 (使用delivery_status字段)
        $completed = $query->where('delivery_status', 2)->count();

        return [
            'total' => $total,
            'total_amount' => $totalAmount,
            'pending' => $pending,
            'completed' => $completed
        ];
    }

    /**
     * 获取跟进统计
     */
    private function getFollowupStats($userId, $departmentId)
    {
        $followupModel = new Followup();

        // 构建查询条件
        $where = [];
        if (!$this->isAdmin()) {
            if ($this->isManager()) {
                $where[] = ['department_id', '=', $departmentId];
            } else {
                // 普通员工只能看到自己的跟进记录，使用user_id字段
                $where[] = ['user_id', '=', $userId];
            }
        }

        // 总跟进记录数
        $total = $followupModel->where($where)->count();

        // 本周跟进记录数
        $weekStart = strtotime('monday this week');
        $weekCount = $followupModel->where($where)->where('create_time', '>=', $weekStart)->count();

        // 待跟进记录数
        $pending = $followupModel->where($where)
            ->where('next_followup_time', '>', time())
            ->where('next_followup_time', '<', time() + 7 * 24 * 3600) // 7天内
            ->count();

        return [
            'total' => $total,
            'week_count' => $weekCount,
            'pending' => $pending
        ];
    }

    /**
     * 获取审核统计
     */
    private function getReviewStats($userId, $departmentId)
    {
        $reviewModel = new Review();

        // 构建查询条件，使用正确的review_user_id字段实现数据权限控制
        $where = [];
        
        // 如果不是管理员或经理，只统计与当前用户相关的审核记录
        if (!$this->isAdmin() && !$this->isManager()) {
            $where[] = ['review_user_id', '=', $userId];
        }
        
        // 待审核记录数
        $pendingWhere = $where;
        $pendingWhere[] = ['status', '=', 1];
        $pending = $reviewModel->where($pendingWhere)->count();

        // 今日审核记录数
        $todayStart = strtotime('today');
        $todayWhere = $where;
        $todayWhere[] = ['review_time', '>=', $todayStart];
        $todayCount = $reviewModel->where($todayWhere)->count();

        return [
            'pending' => $pending,
            'today_count' => $todayCount
        ];
    }

    /**
     * 检查是否为管理员（超级管理员）
     */
    private function isAdmin()
    {
        $userId = $this->getUserId();
        if (!$userId) return false;

        $userInfo = Db::name('admin')
            ->field('group_id')
            ->where('id', $userId)
            ->find();

        return $userInfo && $userInfo['group_id'] == 1;
    }

    /**
     * 检查是否为部门经理
     */
    private function isManager()
    {
        $userId = $this->getUserId();
        if (!$userId) return false;

        $userInfo = Db::name('admin')
            ->field('group_id')
            ->where('id', $userId)
            ->find();

        return $userInfo && $userInfo['group_id'] == 2;
    }

    /**
     * 获取待办事项
     */
    public function getTodos()
    {
        try {
            $userId = $this->getUserId();
            $departmentId = $this->getUserDepartmentId();

            $todos = [];

            // 获取待审核订单
            $orderWhere = [];
            if (!$this->isAdmin()) {
                if ($this->isManager()) {
                    // 部门经理只能看到本部门的订单
                    $orderWhere[] = ['user_id', 'in', function($q) use ($departmentId) {
                        $q->table('admin')->where('did', $departmentId)->field('id');
                    }];
                } else {
                    // 普通员工只能看到自己的订单
                    $orderWhere[] = ['user_id', '=', $userId];
                }
            }

            $pendingOrders = Db::name('crm_order')
                ->where($orderWhere)
                ->where('approval_status', 0) // 待审核状态 (0=未审核, 1=已通过, 2=已拒绝)
                ->field('id, customer_name, order_no, create_time')
                ->order('create_time', 'desc')
                ->limit(5)
                ->select();

            foreach ($pendingOrders as $order) {
                $orderTitle = $order['customer_name'] ?: '订单编号: ' . ($order['order_no'] ?: $order['id']);
                $todos[] = [
                    'type' => '审核',
                    'title' => '待审核订单: ' . $orderTitle,
                    'time' => date('Y-m-d', $order['create_time']),
                    'id' => $order['id']
                ];
            }

            return $this->success($todos, '获取待办事项成功');
        } catch (\Exception $e) {
            return $this->error('获取待办事项失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取最近跟进记录
     */
    public function getRecentFollowups()
    {
        try {
            $userId = $this->getUserId();
            $departmentId = $this->getUserDepartmentId();

            // 构建查询条件
            $where = [];
            if (!$this->isAdmin()) {
                if ($this->isManager()) {
                    $where[] = ['user_id', 'in', function($q) use ($departmentId) {
                        $q->table('admin')->where('did', $departmentId)->field('id');
                    }];
                } else {
                    $where[] = ['user_id', '=', $userId];
                }
            }

            // 获取最近5条跟进记录
            $followups = Db::name('crm_followup')
                ->alias('f')
                ->field('
                    f.id,
                    f.followup_time,
                    f.content,
                    f.followup_type,
                    c.name as customer_name,
                    u.name as user_name
                ')
                ->leftJoin('crm_customer c', 'f.customer_id = c.id')
                ->leftJoin('admin u', 'f.user_id = u.id')
                ->where($where)
                ->where(function($q) {
                    $q->whereNull('c.delete_time')
                      ->whereOr('c.delete_time', 0)
                      ->whereOr('c.delete_time', '');
                })
                ->order('f.followup_time', 'desc')
                ->limit(5)
                ->select();

            $result = [];
            foreach ($followups as $item) {
                // 根据跟进类型设置时间线样式
                $typeMap = [
                    1 => 'primary',   // 电话
                    2 => 'success',   // 微信
                    3 => 'warning',   // 邮件
                    4 => 'info',      // 拜访
                    5 => 'danger'     // 会议
                ];

                $result[] = [
                    'time' => date('Y-m-d H:i', $item['followup_time']),
                    'type' => $typeMap[$item['followup_type']] ?? 'info',
                    'customerName' => $item['customer_name'] ?? '未知客户',
                    'content' => $item['content'] ?? '',
                    'userName' => $item['user_name'] ?? '未知用户'
                ];
            }

            return $this->success($result, '获取最近跟进成功');
        } catch (\Exception $e) {
            return $this->error('获取最近跟进失败: ' . $e->getMessage());
        }
    }
}